package file.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES 高级数据加密标准
 * 对称加密
 * @author hh
 * @since 2024/12/7
 */
public class AESUtil {

    private static final Logger log = LoggerFactory.getLogger(AESUtil.class);

    // AES密钥算法
    public static final String KEY_ALGORITHM = "AES";
    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "/ECB/PKCS5Padding";
    public static final String ALGORITHM_KEY = "LQnPRQJLvwi4tT8oLqLxDw==";

    private AESUtil() {
    }

    public static String generateKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(128, new SecureRandom());
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    public static Cipher getCipher(int encryptMode) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(ALGORITHM_KEY.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM);
        // 获取Cipher实例，java8中AES默认使用ECB模式和PKCS5Padding填充方式
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM + CIPHER_ALGORITHM);
        cipher.init(encryptMode, secretKeySpec);
        return cipher;
    }

    public static String encrypt(String plainString) throws Exception {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
        byte[] cipherBytes = cipher.doFinal(plainString.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(cipherBytes);
    }

    public static String decrypt(String cipherString) throws Exception {
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
        byte[] cipherBytes = cipher.doFinal(Base64.getDecoder().decode(cipherString));
        return new String(cipherBytes);
    }

}
